#include "tcp_socket.h"
#include <iostream>

using namespace std;

tcp_socket::tcp_socket(const char *pip, int pport):sockfd(0), listfd(0)
{
	strcpy(ip, pip);
	port = pport;
}

tcp_socket::~tcp_socket()
{
	close(sockfd);

	close(listfd);
}

int tcp_socket::init_socket()
{
	if (false == socket())
		return -1;

	if (false == bind())
		return -1;

	if (false == listen())
		return -1;

	return listfd;
}

bool tcp_socket::socket()
{
	listfd = ::socket(AF_INET, SOCK_STREAM, 0);
	if (listfd < 0)
		return false;

	int flag = 0;
	setsockopt(listfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&flag, sizeof(flag));

	return true;
}

bool tcp_socket::bind()
{
	struct sockaddr_in svraddr;
	svraddr.sin_family = AF_INET;
	svraddr.sin_port = htons(port);
	if (inet_pton(AF_INET, ip, &svraddr.sin_addr) < 0)
		return false;

	int ret = 0;

	ret = ::bind(listfd, (struct sockaddr *)&svraddr, sizeof(svraddr));
	if (ret < 0)
		return false;

	return true;
}

bool tcp_socket::listen()
{
	if (::listen(listfd, 10) < 0)
		return false;

	return true;
}

int tcp_socket::accept()
{
	struct sockaddr_in cliaddr;
	socklen_t addrlen = sizeof(struct sockaddr_in);

	sockfd = ::accept(listfd, (struct sockaddr *)&cliaddr, &addrlen);
	if (sockfd < 0)
		return -1;

	cout << "client ip: " << inet_ntoa(cliaddr.sin_addr) << endl;
	return sockfd;
}

int tcp_socket::recv(char *buf, int len, int flag)
{
	return (::recv(sockfd, buf, len, flag));
}

int tcp_socket::send(const char *buf, int len, int flag)
{
	return (::send(sockfd, buf, len, flag));
}

int tcp_socket::get_socket()
{
	return listfd;
}

